#include "d3d.h"
#include "d3d_image.h"
#include "..\engine\error.h"
#include "d3d_texture.h"

D3DImage::D3DImage(CD3D9Device* const pDevice) : IResource(pDevice)
{
	m_alpha = (0.0f); 
	pTexutre = NULL; 
	screenPosition = D3DXVECTOR2(0,0); 
	m_alpha = 1.0f; 
	D3DXMatrixIdentity(&m_scale);
	m_Draw = false; 
}

void D3DImage::Draw()
{
	m_Draw = true; 
}

void D3DImage::SetPosition(const Vector2f &position)
{
	screenPosition.x = position.x; 
	screenPosition.y = position.y; 
}

void D3DImage::SetAlpha(const float alpha)
{
	m_alpha = CLAMP(alpha, 1.0f, 0.0f); 
}

void D3DImage::SetScale(const float value)
{
	if(value < 0.0f)
		D3DXMatrixIdentity(&m_scale);
	else
		D3DXMatrixScaling(&m_scale, value, value, value);
}

Vector2f D3DImage::GetDimensions() {
	Vector2f pDim = pTexutre->GetDimensions();
	DeviceSettings devSettings = GetDevice()->GetDeviceSettings();

	return Vector2f((float)pDim.x / (float)devSettings.screenWidth,(float)pDim.y / (float)devSettings.screenHeight);
}

string D3DImage::GetType() const
{
	return string("D3DImage"); 
}
HRESULT D3DImage::Reload()
{
	return S_OK; 
}
HRESULT D3DImage::Release()
{
	m_IsValid = false; 
	pTexutre = NULL; 
	m_alpha = 0; 
	D3DXMatrixIdentity(&m_scale);
	m_Draw = false; 

	return S_OK; 
}

HRESULT CD3D9Device::CreateSprite(D3DImage** pOut,const string& filename)
{
	D3DImage *pImage = NULL; 
	D3DTexture2D* pTexture = NULL; 
	HRESULT hr;

	do {
		
		if(ISNULL(pOut)) {
			EE_LOGERROR("Bad parameter.");
			hr = E_INVALIDARG;
			break;
		}

		if(!filename.IsValid()) {
			EE_LOGERROR("Bad filename.");
			hr = E_INVALIDARG;
			break;
		}

		//Note that calling this preforms a search through cached textures
		//for duplicate
		if(FAILED(CreateTexture(filename, (Texture**)&pTexture))) {
			EE_LOGERROR("Failed to load texture.");
			hr = E_FAIL;
			break;
		}

		if(!pTexture->GetType().equals("D3DTexture2D")) {
			EE_LOGERROR("Wrong texture resource type. Expected 2D texture.");
			hr = E_UNEXPECTED;
			break;
		}

		pImage = EE_NEW D3DImage(this); 
		if(ISNULL(pImage)) {
			hr = E_OUTOFMEMORY;
			break;
		}

		pImage->pTexutre = pTexture; 
		m_Sprites.Add(pImage); 
		*pOut = pImage; 

		return S_OK; 
	
	}while(false);

	if(pImage) {
		pImage->Release();
		EE_SAFEDELETE(pImage);
	}
	pTexture = NULL;
	*pOut= NULL;

	return E_FAIL; 
}
